package org.etom.impl.ui.jobs;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.osgi.util.NLS;
import org.etom.connector.datatypes.IMoodleModule;
import org.etom.impl.ui.Activator;
import org.etom.impl.ui.util.CommonMessages;
import org.etom.impl.ui.util.Logger;
import org.etom.impl.ui.util.ResourceManager;
import org.etom.impl.ui.wizards.WizardsMessages;

public class CreateProjectJob extends Job {

  private String projectName;
  private String location;
  private IMoodleModule moodleModule;
  private IProject project;
  
  public CreateProjectJob(String projectName, String location, IMoodleModule resource) {
    super(CommonMessages.Create_Project_Progress_Name);
    this.projectName = projectName;
    this.location = location;
    this.moodleModule = resource;
  }
  
  public CreateProjectJob(IProject project, IMoodleModule moodleModule) {
    this(project.getName(), project.getLocation().toString(), moodleModule);
    this.project = project;
  }
  
  @Override
  protected IStatus run(IProgressMonitor monitor) {
    try {
      if (null != project) {
        ResourceManager.createMoodleProject(project, moodleModule);
      } else {
        ResourceManager.createProject(projectName, location, moodleModule);
      }
      return Status.OK_STATUS;
    } catch (Exception e) {
      String errorMessage = NLS.bind(
          WizardsMessages.DownloadAs_Wizard_Create_Project_Fail, projectName); 
      Logger.ERROR(errorMessage, e);
      return new Status(IStatus.ERROR, Activator.PLUGIN_ID, errorMessage);
    }
  }

}
